package org.rainbowinverted.charging.device.connect.ykc.server.handler;

import cn.hutool.core.util.HexUtil;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcDeviceTimeSyncIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcMessageIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.out.YkcDeviceTimeSyncOut;
import org.rainbowinverted.charging.device.connect.ykc.server.util.Cp56Time2aUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 时间同步处理器
 * @author hehuaiping
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class YkcTimeSyncHandler extends YkcAbstractHandler<YkcDeviceTimeSyncIn, YkcDeviceTimeSyncOut> {
    @Override
    public void read(ChannelHandlerContext channel, YkcMessageIn message) {
        ByteBuf messageBody = message.getMessageBody();
        // 设备编号
        Long deviceNo = readDeviceNo(messageBody);
        // 时间
        byte[] timeBytes = new byte[7];
        messageBody.readBytes(timeBytes);
        LocalDateTime time = Cp56Time2aUtils.hexCp56Time2aToTime(HexUtil.encodeHexStr(timeBytes));
        YkcDeviceTimeSyncIn timeSyncIn = new YkcDeviceTimeSyncIn(deviceNo, time);
        log.info("time sync resp info: {}", timeSyncIn);
    }

    @Override
    public void write(ByteBuf byteBuf, YkcDeviceTimeSyncOut ykcDeviceTimeSyncOut) {
        writeDeviceNo(byteBuf, ykcDeviceTimeSyncOut.getDeviceNo());
        // 时间 CP56Time2a 格式
        byteBuf.writeBytes(HexUtil.decodeHex(Cp56Time2aUtils.date2HexStr(ykcDeviceTimeSyncOut.getTime())));
    }
}
